﻿using System;
using System.Collections.Generic;
using System.Text;
using CSLive.searchsoap;
using System.Web;
using CommunityServer.Components;

namespace CSLive.LiveSearch
{
    public class SearchProvider : CommunityServer.Components.SearchProvider
    {
        public override CommunityServer.Components.SearchResultSet Search(CommunityServer.Components.SearchQuery query)
        {
            TimeSpan ts = System.DateTime.Now.TimeOfDay;

            MSNSearchService searchs = new CSLive.searchsoap.MSNSearchService();

            if (!string.IsNullOrEmpty(LiveConfiguration.Instance.getConfigSetting("Live Search Provider", "Proxy Server Url").Value.ToString()))
                searchs.Proxy.GetProxy(new Uri(LiveConfiguration.Instance.getConfigSetting("Live Search Provider", "Proxy Server Url").Value.ToString()));

            SearchRequest searchRequest = new SearchRequest();
            SourceRequest[] sr = new SourceRequest[1];
            sr[0] = new SourceRequest();
            sr[0].Source = SourceType.Web;
            sr[0].Count = query.PageSize;
            sr[0].Offset = query.PageIndex;

            searchRequest.AppID = LiveConfiguration.Instance.getConfigSetting("Live Search Provider", "Application Id").Value.ToString();
            searchRequest.Requests = sr;


            searchRequest.Query = query.QueryText + " site:" + HttpContext.Current.Request.Url.Host.Replace("www", "");
            searchRequest.CultureInfo = CSContext.Current.User.Profile.Language;

            SearchResponse searchResponse;

            searchResponse = searchs.Search(searchRequest);

            SearchResultSet srs = new SearchResultSet();
            SourceResponse sourceResponse = searchResponse.Responses[0];

            srs.TotalRecords = sourceResponse.Total;
            srs.SearchDuration = (Double)(System.DateTime.Now.TimeOfDay.Ticks - ts.Ticks);
            foreach (Result sourceResult in sourceResponse.Results)
            {
                IndexPost ip = new IndexPost();
                if (sourceResult.Url.ToLower().Contains("blogs"))
                    ip.ApplicationType = ApplicationType.Weblog;
                ip.Body = sourceResult.Source;
                ip.FormattedBody = sourceResult.Summary;
                ip.Url = sourceResult.Url;
                ip.Title = sourceResult.Title;
                srs.Posts.Add(ip);
            }
            return srs;

        }
    }
}
